package naga.x.net.impl.pomelo.protocol;

import java.util.Arrays;

/**
 * @see Package
 * @see Message
 * @author yang.li
 *
 */
public class Protocol {
	
	public static byte[] strencode(String str) {
//	    if (typeof Buffer !== "undefined" && ByteArray === Buffer) {
//	      // encoding defaults to 'utf8'
//	      return (new Buffer(str));
//	    } else {
//		if (IOUtils.UTF8.equalsIgnoreCase(DEFAULT_ENCODING)) {
//			try {
//				return str.getBytes(DEFAULT_ENCODING);
//			} catch (UnsupportedEncodingException e) {
//			}
//		}
		int len = str.length();
		byte[] byteArray = new byte[len * 3];
		int offset = 0;
		for (int i = 0; i < len; i++) {
			char charCode = str.charAt(i);
			if (charCode <= 0x7f) {
				byteArray[offset++] = (byte) charCode;
			} else if (charCode <= 0x7ff) {
				byteArray[offset++] = (byte) (0xc0 | (charCode >> 6));
				byteArray[offset++] = (byte) (0x80 | (charCode & 0x3f));
			} else {
				byteArray[offset++] = (byte) (0xe0 | (charCode >> 12));
				byteArray[offset++] = (byte) (0x80 | ((charCode & 0xfc0) >> 6));
				byteArray[offset++] = (byte) (0x80 | (charCode & 0x3f));
			}
		}
		return byteArray.length == offset ? byteArray : Arrays.copyOfRange(byteArray, 0, offset);
//	    }
	}
	
	public static String strdecode(byte[] bytes) {
//	    if(typeof Buffer !== "undefined" && ByteArray === Buffer) {
//	      // encoding defaults to 'utf8'
//	      return buffer.toString();
//	    } else {
//		if (IOUtils.UTF8.equalsIgnoreCase(DEFAULT_ENCODING)) {
//			try {
//				return new String(bytes, DEFAULT_ENCODING);
//			} catch (UnsupportedEncodingException e) {
//			}
//		}
		int len = bytes.length;
		char[] array = new char[len];
		int pos = 0;
		int offset = 0;
		while (offset < len) {
			int b = bytes[offset++] & 0xff;
			if (b < 128) {
				array[pos++] = (char) b;
			} else if (b < 224) {
				int b2 = bytes[offset++] & 0xff;
				array[pos++] = (char) (((b & 0x1f) << 6) + (b2 & 0x3f));
			} else {
				int b2 = bytes[offset++] & 0xff;
				int b3 = bytes[offset++] & 0xff;
				array[pos++] = (char) (((b & 0x0f) << 12) + ((b2 & 0x3f) << 6) + (b3 & 0x3f));
	        }
		}
//	    }
		return new String(array, 0, pos);
	  }
	
}
